package com.szgr.baoyin.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;


import com.szgr.baoyin.R;
import com.szgr.baoyin.model.BrandType;

import java.util.Calendar;
import java.util.Date;


/**
 * Created by root on 15-4-23.
 */
public class PopMenuDate {

    private PopupWindow mPopupWindow;
    private Context context;
    private int request;
    private static final int DEFAULT_REQUEST = 3000;
    private LinearLayout ll_cancel;
    private LinearLayout ll_confirm;
    private TextView tv_popup_menu_title;
    private IPopupWindowsConfirm mListener;
    private NumberPicker np1, np2, np3 ,np4 ,np5;
    /**
     * 年月日
     */
    private String str1, str2, str3;
    /**
     * 最大年份和最小年份
     */
    private int maxYear = 2299, minYear = 1900;

    private String[] date = null;
    private TextView textView;
    
    private TextView yearMileage;//里程页面分段显示日期
    private TextView dateMileage;
    
    private String maxDate = "";
    private String minDate = "";
    private boolean needTime = false;//是否需要 时间
    private View ll_time;
    private BrandType currentBrand;
    private boolean needJudge = false;

    //    public PopMenuDate() {
//
//    }

    public PopMenuDate(Context context) {
        this(context, DEFAULT_REQUEST);
    }

    public PopMenuDate(boolean needJudge , Context context) {
        this(context, DEFAULT_REQUEST);
        this.needJudge = needJudge;
    }

    public PopMenuDate(Context context, boolean needTime){
        this(context,DEFAULT_REQUEST);
        this.needTime = needTime;
        if(needTime){
            ll_time.setVisibility(View.VISIBLE);
        }
    }

    public PopMenuDate(final Context context, int request) {
        this.context = context;
        this.request = request;

        View view = OnCreateView(context);
        view.setFocusableInTouchMode(true);
        mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());//new ColorDrawable(Color.TRANSPARENT));
        mPopupWindow.setAnimationStyle(R.style.popup_animation);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (context instanceof Activity){
                    backgroundAlpha(1.0f,(Activity)context);
                }
            }
        });
    }

    private View OnCreateView(Context context) {
        this.context = context;
        View view = LayoutInflater.from(context).inflate(R.layout.popup_menu_date, null);

        ll_cancel = (LinearLayout) view.findViewById(R.id.ll_cancel);
        ll_confirm = (LinearLayout) view.findViewById(R.id.ll_confirm);
        tv_popup_menu_title = (TextView) view.findViewById(R.id.tv_popup_menu_title);

        np1 = (NumberPicker) view.findViewById(R.id.np1);
        np2 = (NumberPicker) view.findViewById(R.id.np2);
        np3 = (NumberPicker) view.findViewById(R.id.np3);

        np4 = (NumberPicker) view.findViewById(R.id.np4);
        np5 = (NumberPicker) view.findViewById(R.id.np5);
        ll_time = view.findViewById(R.id.time);

        np1.setClickable(false);
        np2.setClickable(false);
        np3.setClickable(false);
        np4.setClickable(false);
        np5.setClickable(false);

        setListener();
        return view;
    }

    public void show(View parent, int width, int height) {
        if (mPopupWindow != null) {
            initDate();
            mPopupWindow.showAtLocation(parent, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
            mPopupWindow.update();
            if (context instanceof Activity) {
                backgroundAlpha(0.5f, (Activity) context);
            }
        }
    }

    public void dismiss() {
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
        }
    }

    public boolean isShowing() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param date yyyy-MM-dd
     */
    public void setDate(String date) {
        this.date = date.split("-");
    }

    /**
     * 初始化时间
     */
    private void initDate() {
        np1.setMaxValue(maxYear);
        np1.setMinValue(minYear);
        np1.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

            @Override
            public void onValueChange(NumberPicker numberPicker, int previous, int current) {
                str1 = np1.getValue() + "";

                if (Integer.parseInt(str1) % 4 == 0
                        && Integer.parseInt(str1) % 100 != 0
                        || Integer.parseInt(str1) % 400 == 0) {
                    if (str2.equals("1") || str2.equals("3") || str2.equals("5") || str2.equals("7") || str2.equals("8") || str2.equals("10") || str2.equals("12")) {
                        np3.setMaxValue(31);
                        np3.setMinValue(1);
                    } else if (str2.equals("4") || str2.equals("6") || str2.equals("9") || str2.equals("11")) {
                        np3.setMaxValue(30);
                        np3.setMinValue(1);
                    } else {
                        np3.setMaxValue(29);
                        np3.setMinValue(1);
                    }

                } else {
                    if (str2.equals("1") || str2.equals("3") || str2.equals("5") || str2.equals("7") || str2.equals("8") || str2.equals("10") || str2.equals("12")) {
                        np3.setMaxValue(31);
                        np3.setMinValue(1);
                    } else if (str2.equals("4") || str2.equals("6") || str2.equals("9") || str2.equals("11")) {
                        np3.setMaxValue(30);
                        np3.setMinValue(1);
                    } else {
                        np3.setMaxValue(28);
                        np3.setMinValue(1);
                    }
                }
                checkDate();
            }
        });

        np2.setMaxValue(12);
        np2.setMinValue(1);
        np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

            @Override
            public void onValueChange(NumberPicker numberPicker, int previous, int current) {
                // TODO Auto-generated method stub
                if (current == 1 && previous == 12) {
                    if (np1.getValue() < np1.getMaxValue()) {
                        np1.setValue(np1.getValue() + 1);
                    }
                } else if (previous == 1 && current == 12) {
                    if (np1.getValue() > np1.getMinValue()) {
                        np1.setValue(np1.getValue() - 1);
                    }
                }
                checkDay();
                checkDate();
            }
        });

        np3.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

            @Override
            public void onValueChange(NumberPicker numberPicker, int previous, int current) {
                // TODO Auto-generated method stub
                str3 = np3.getValue() + "";
                int nowMonth = np2.getValue();
                if (current == 1) {
                    if (previous == 30 || previous == 31 || previous == 29 || previous == 28) {
                        if (nowMonth != 12) {
                            np2.setValue(nowMonth + 1);
                        } else {
                            np2.setValue(1);
                            if (np1.getValue() < np1.getMaxValue()) {
                                np1.setValue(np1.getValue() + 1);
                            }
                        }
                    }
                } else if (previous == 1) {
                    if (current == 30 || current == 31 || current == 29 || current == 28) {
                        if (nowMonth != 1) {
                            np2.setValue(nowMonth - 1);
                            checkDay();
                            np3.setValue(np3.getMaxValue());
                        } else {
                            np2.setValue(12);
                            if (np1.getValue() > np1.getMinValue()) {
                                np1.setValue(np1.getValue() - 1);
                            }
                        }
                    }
                }
                checkDay();
                checkDate();
            }
        });

        if (date != null) {
            str1 = date[0];
            str2 = date[1];
            str3 = date[2];
            np1.setValue(Integer.parseInt(date[0]));
            np2.setValue(Integer.parseInt(date[1]));
            checkDay();
            np3.setValue(Integer.parseInt(date[2]));
//            Calendar calendar = Calendar.getInstance();
//            int hour = calendar.get(Calendar.HOUR_OF_DAY);
//            int minute = calendar.get(Calendar.MINUTE);
//            np4.setValue(hour);
//            np5.setValue(minute);
        } else {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            str1 = String.valueOf(year);
            str2 = String.valueOf(month);
            str3 = String.valueOf(day);
            np1.setValue(year);
            np2.setValue(month);
            checkDay();
            np3.setValue(day);
            np4.setValue(hour);
            np5.setValue(minute);
        }
//        checkDay();
//        np3.setMaxValue(31);
//        np3.setMinValue(1);
        np1.setFocusable(true);
        np1.setFocusableInTouchMode(true);

        np4.setMaxValue(17);
        np4.setMinValue(8);

        np5.setMinValue(0);
        np5.setMaxValue(59);
        np5.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int previous, int current) {
                int nowHour = np4.getValue();
                if(current == 1){
                    if(previous == 0){
                        if(nowHour != 23) {
                            np4.setValue(nowHour + 1);
                        }else{
                            np4.setValue(1);
                        }
                    }
                }else if(current == 0){
                    if(previous == 1){
                        if(nowHour != 0) {
                            np4.setValue(nowHour - 1);
                        }else{
                            np4.setValue(23);
                        }
                    }
                }
            }
        });
    }

    private void checkDate() {
    	if(maxDate!=null&&!"".equals(maxDate)){
	    	String date = np1.getValue()+"-"+np2.getValue()+"-"+np3.getValue();
	    	if(DateUtils.compare_date(date,maxDate)>0){
	    		String [] maxDateArr = maxDate.split("-");
	    		np1.setValue(Integer.parseInt(maxDateArr[0]));
	    		np2.setValue(Integer.parseInt(maxDateArr[1]));
	    		np3.setValue(Integer.parseInt(maxDateArr[2]));
	    	}
    	}
    	if(minDate!=null&&!"".equals(minDate)){
	    	String date = np1.getValue()+"-"+np2.getValue()+"-"+np3.getValue();
	    	if(DateUtils.compare_date(date,minDate)<0){
	    		String [] minDateArr = minDate.split("-");
	    		np1.setValue(Integer.parseInt(minDateArr[0]));
	    		np2.setValue(Integer.parseInt(minDateArr[1]));
	    		np3.setValue(Integer.parseInt(minDateArr[2]));
	    	}
    	}
    }
    
    public void setMaxDate(String maxDate) {
    	this.maxDate = maxDate;
    }
    
    public void setMinDate(String minDate) {
    	this.minDate = minDate;
    }
    
    private void checkDay() {
        str2 = np2.getValue() + "";
        if (str2.equals("1") || str2.equals("3") || str2.equals("5") || str2.equals("7") || str2.equals("8") || str2.equals("10") || str2.equals("12")) {
            np3.setMaxValue(31);
            np3.setMinValue(1);
        } else if (str2.equals("4") || str2.equals("6") || str2.equals("9") || str2.equals("11")) {
            np3.setMaxValue(30);
            np3.setMinValue(1);
        } else {
            if (Integer.parseInt(str1) % 4 == 0
                    && Integer.parseInt(str1) % 100 != 0
                    || Integer.parseInt(str1) % 400 == 0) {
                np3.setMaxValue(29);
                np3.setMinValue(1);
            } else {
                np3.setMaxValue(28);
                np3.setMinValue(1);
            }
        }
    }

    /**
     * 单击事件
     */
    private void setListener() {
        //取消
        ll_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
//                    mListener.notifyDismiss();
                }
                if (mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                }
//                if (context instanceof Activity){
//                    backgroundAlpha(1.0f, (Activity)context);
//                }
            }
        });
        //确定
        ll_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String date = np1.getValue() + "-" + checkNum(np2.getValue()) + "-" + checkNum(np3.getValue());
                if(needJudge){
//                    int cY = MyTool.getCurrentYear();
//                    int cM = MyTool.getCurrentMonth();
//                    int cD = MyTool.getCurrentDay();
                    int y = np1.getValue();
                    int m = np2.getValue();
                    int d = np3.getValue();
                    Date date1 = new Date(y-1900,m - 1,d);

                    if(date1.after(new Date())){
                        mListener.notifyDataChanged(date,907);
                        return;
                    }
                }
                if(currentBrand != null) {
                    currentBrand.setDate(date);
                }
                if(needTime){
                    int value2 = np4.getValue();
                    date = date + " " + checkNum(value2) + ":" + checkNum(np5.getValue()) + ":00";
                }
                if (mListener != null) {
                    mListener.notifyDataChanged(date, request);
                }
                if (mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                }
                if (textView != null){
                    textView.setText(date);
                }
            }
        });
    }
    private String checkNum(int num){

        String str = String.valueOf(num);
        if (num < 10){
            return "0" + str;
        }else{
            return str;
        }
    }

    /**
     * 保银项目需求
     * @param currentBrand
     */
    public void setModel(BrandType currentBrand) {
        this.currentBrand = currentBrand;
    }

    /**
     * 选中的接口
     */
    public interface IPopupWindowsConfirm {
        /**
         * 确定按钮
         *
         * @param date    选中的时间
         * @param request 请求标识码
         */
        void notifyDataChanged(String date, int request);

        /**
         * 取消按钮
         */
//        void notifyDismiss();
    }

    /**
     * 改变popuWindow显示时的背景颜色
     *
     * @param bgAlpha , float popAlpha
     */
    private void backgroundAlpha(float bgAlpha, Activity activity) {
        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
        params.alpha = bgAlpha;
        activity.getWindow().setAttributes(params);
    }


    public void setmListener(IPopupWindowsConfirm mListener) {
        this.mListener = mListener;
    }

    public void setTitle(String title) {
        this.tv_popup_menu_title.setText(title);
    }

    public void setTextViewOfShow(TextView textView){
        this.textView = textView;
    }
    
    public void setMaxYear(int maxYear) {
        this.maxYear = maxYear;
    }

    public void setMinYear(int minYear) {
        this.minYear = minYear;
    }
}
